﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;

namespace Property.Reloaders
{
    public class ReactiveReloader<T> : OutReloader<T>
    {
        public ReactiveReloader(ISequenceConveyor<T> sequenceConveyor, Func<T> getValue, Action<T> applyValue, Action<bool> applyStatus)
            : base(applyValue, applyStatus)
        {
            if (sequenceConveyor == null) throw new ArgumentNullException("sequenceConveyor");

            _GetValueSequence = sequenceConveyor.Create(getValue);

            if (_GetValueSequence == null) throw new NotSupportedException(StringsReactive.CANT_OBTAIN_SEQUENCE);
        }

        //=//

        private readonly IObservable<T> _GetValueSequence;

        private IDisposable LoadingProcessState;

        public override void Go()
        {
            if (LoadingProcessState != null) LoadingProcessState.Dispose();

            _ApplyStatus(true);

            LoadingProcessState = _GetValueSequence
                .Subscribe(cur =>
                {
                    _ApplyStatus(false);
                    _ApplyValue(cur);
                });
        }

        public override void Dispose()
        {
            if (LoadingProcessState != null) LoadingProcessState.Dispose();
        }
    }
}
